<template>
  <div class="app-page">
    <el-table-form ref="form" :max-cols="4" :model="query">
      <el-form-item label-width="0" class="merge-item">
        <el-select v-model="type" style="width: 170px; margin-right: 2px;">
          <el-option label="订单号" value="orderCode">订单号</el-option>
          <el-option label="芯片编码" value="chipCode">芯片编码</el-option>
          <el-option label="发现人" value="deliver">发现人</el-option>
          <el-option label="客户地址" value="csmAddress">客户地址</el-option>
          <el-option label="客户名称" value="csmName">客户名称</el-option>
          <el-option label="电话" value="csmPhone">电话</el-option>
        </el-select>
        <el-input v-model.trim="text" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="发现时间:" class="merge-item" :table-form-merge="1.1">
        <el-date-picker
          v-model="date"
          type="daterange"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :clearable="false"
          :default-time="['00:00:00', '23:59:59']"
        />
      </el-form-item>
      <el-form-item label="所属机构:" prop="orgSNNo">
        <el-tree-select
          v-model="query.orgSNNo"
          clearable
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData
          }"
          :tree-params=" {
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props:{
              value:'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData
          }"
        />
      </el-form-item>
      <template v-slot:btns>
        <el-button v-permission="1" :loading="$loadingPlugin.fetchData" type="primary" icon="el-icon-search" @click="search">查询</el-button>
      </template>
    </el-table-form>

    <div style="margin-bottom: 10px;" class="btn-group">
      <div>
        <el-button :loading="$loadingPlugin.exportFile" type="primary" icon="el-icon-download" @click="exportFile">导出</el-button>
      </div>
    </div>
    <div style="margin-bottom: 10px;">
      <span style="color: red;">说明：回收空瓶的上次配送地址和本次回收地址不符，算一次窜瓶记录<span style="color: #999;">(注:配送员配送时未扫重瓶会导致上次配送地址为空)</span></span>
    </div>
    <lb-table
      ref="lbTable"
      v-loading="$loadingPlugin.fetchData"
      v-el-height-adaptive-table="{bottomOffset:10}"
      border
      highlight-current-row
      element-loading-text="加载中"
      :column="tableData.column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      custom-column
      @fetch="fetchData"
    />
    <location ref="location" />
    <bottle-detail ref="bottleDetail" />
    <OrderFlowInfoModal ref="OrderFlowInfoModal" />
  </div>
</template>

<script>
  import { gasExceptionQueryList, queryGasExceptionExport } from '@/api'
  import { parseTime } from '@/utils'
  import getTreeData from '@/utils/jsonTree'
  import { mapGetters } from 'vuex'
  import moment from 'dayjs'
  import BottleDetail from '../../components/BottleDetail'

  export default {
    name: 'receiptManage',
    components: {
      Location: require('../../components/CsmLocation').default,
      BottleDetail,
      OrderFlowInfoModal: require('../../components/OrderFlowInfoModal').default
    },
    data() {
      return {
        treeData: [],
        type: 'orderCode',
        date: [moment().startOf('day'), moment().endOf('day')],
        text: '',
        query: {
          orgSNNo: ''
        },
        searchParams: {},
        tableData: {
          total: 0,
          column: [
            {
              type: 'index',
              fixed: true,
              align: 'center'
            },
            {
              prop: 'address',
              label: '地图',
              width: 50,
              align: 'center',
              fixed: true,
              render: (h, { row }) => <span onClick={() => this.openLocation(row)}>{row.lon && row.lat && <i class='el-icon-location' style='color: #126edc;cursor: pointer;'/>}</span>
            },
            {
              prop: 'orderCode',
              label: '订单号',
              fixed: true
            },
            { label: '所属机构', prop: 'orgName', width: 120 },
            { label: '客户名称', prop: 'csmName' },
            { label: '客户电话', prop: 'csmPhone', width: 120 },
            { label: '本次回收地址', prop: 'csmAddress', width: 200 },
            { label: '上次配送地址', prop: 'preCsmAddress', width: 200 },
            { label: '发现人', prop: 'deliver' },
            { label: '发现时间', prop: 'createTime', width: 150,
              render: (h, { row }) => <span>{ row.createTime && parseTime(row.createTime, '{y}-{m}-{d} {h}:{i}') }</span>
            },
            { label: '异常芯片号', prop: 'chipCode', width: 120,
              render: (h, { row }) => <el-link underline={false} onClick={() => this.openDetail(row)}>{row.chipCode}</el-link>
            }
          ],
          data: []
        }
      }
    },
    computed: {
      ...mapGetters([
        'orgList', 'exportDomain'
      ])
    },
    async created() {
      await this.getTreeData()
    },
    methods: {
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map(item => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize
        }
        query[this.type] = this.text
        if (this.date && this.date.length > 0) {
          query.createTime = this.date[0]
          query.createTimeEnd = this.date[1]
          const diff = moment(this.date[1]).diff(moment(this.date[0]), 'days')
          if (diff > 93) {
            this.$message.error('发现时间最大支持查询3个月')
            return
          }
        }
        const res = await gasExceptionQueryList(query)
        this.searchParams = query
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
      },
      async openDetail(row) {
        await this.$refs.bottleDetail.open(row, null, 'fleeCylinder')
      },
      async openLocation(row) {
        await this.$refs.location.open(row)
      },
      // 流转信息
      async update(row) {
        await this.$refs.OrderFlowInfoModal.open(row.orderCode)
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 导出
      exportFile() {
        const _this = this
        this.$confirm(`确定导出数据？`, '提示', {
          type: 'warning'
        }).then(() => {
          const copyColumn = JSON.parse(JSON.stringify(this.tableData.column))
          const str = {}
          copyColumn.forEach(item => {
            str[item.prop] = item.label
          })
          queryGasExceptionExport({
            paramInfo: _this._getQuery(_this.searchParams),
            kv: str // 表格列
          }).then((res) => {
            window.open(`${this.exportDomain}/page/export/frame?key=${res.data}`, '_blank')
          })
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .el-form-item .el-form-item {
    margin-bottom: 0;
  }
  .merge-item {
    /deep/ .el-form-item__content {
      display: flex;
    }
  }
  .btn-group {
    display: flex;
    justify-content: space-between;
  }
</style>
